package name.bingo.bing.pay.gateway.controller;
/**
 * create by yanbing on 2018/11/8 17:01
 */

import com.alibaba.dubbo.config.annotation.Reference;
import name.bingo.bing.pay.gateway.dao.PayLogDao;
import name.bingo.bing.pay.gateway.entity.PayLog;
import name.bingo.bing.pay.service.message.api.MessageService;
import name.bingo.bing.pay.service.message.entity.TractionMessage;
import name.bingo.bing.pay.service.trade.api.TradeWriteService;
import name.bingo.bing.pay.utils.IdGen;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @param:
 * @return:
 * @auther: yanbing
 * @date: 2018/11/8 17:01
 **/
@RestController
@RequestMapping("pay")
public class OrderPayController {
    Logger logger=LoggerFactory.getLogger(OrderPayController.class);

    @Value("${bank-message}")
    private String BankMessage;
    @Reference
    private TradeWriteService tradeWriteService;
    @Reference
    private MessageService messageService;
    @Autowired
    private PayLogDao payLogDao;


    @RequestMapping("initOrderPay")
    public String initOrderPay(HttpServletRequest request, HttpServletResponse response,@RequestBody String paramJson){
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        System.out.println(jsonObject);
        Map<String,Object> order = jsonObject;
        System.out.println(order);
        String orderId = tradeWriteService.orderInit(order);
        return orderId;
    }
    //模拟支付回调接口
    @RequestMapping("notify")
    public String notify(HttpServletRequest request, HttpServletResponse response,@RequestBody String paramJson){
        Map<String,Object> notifyMap = JSONObject.fromObject(paramJson);
        try{
        //先保存支付回调记录
            System.out.println("1231231:"+(String)paramJson);
            PayLog paylog=new PayLog(IdGen.idGen(),(String)notifyMap.get("out_trade_no"),(String)notifyMap.get("transaction_id"),
                    (String)paramJson,(String)notifyMap.get("result_code"));
            payLogDao.insert(paylog);
        //发送消息异步处理订单回调
        TractionMessage tractionMessage=new TractionMessage((String)notifyMap.get("transaction_id"),paramJson,BankMessage);
        messageService.saveAndSend(tractionMessage);
        System.out.println("notify:"+notifyMap.get("out_trade_no"));
        }catch (Exception e){
            logger.info("出错了："+e.getMessage());
            return "error";
        }
        return "ok:";
    }
}
